<template>
	<view class="home-container">
		<!-- 小区选择 -->
		<view class="community-wrapper">
			<view class="community-info">
				<view class="left">
					<text class="community-name">{{ communityDisplayName }}</text>
					<uni-icons type="bottom" size="12" color="#666"></uni-icons>
				</view>
				<view class="switch-btn" @click="showCommunityPicker">切换小区</view>
			</view>
		</view>


		<!-- 骨架屏 -->
		<template v-if="loading">
			<view class="cards-grid">
				<view class="service-card skeleton" v-for="i in 4" :key="i"></view>
			</view>
		</template>

		<!-- 服务卡片 -->
		<view class="cards-wrapper" v-else>
			<view class="cards-grid">
				<view class="service-card" v-for="service in services" :key="service.id" @click="onCardClick(service)"
					hover-class="card-hover">
					<view class="card-icon" :style="{ backgroundColor: service.color }">
						<uni-icons :type="service.icon" size="32" color="#fff" />
					</view>
					<view class="card-content">
						<text class="card-title">{{ service.title }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 小区选择弹窗 -->
		<uni-popup ref="communityPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">选择小区</text>
					<text class="popup-close" @click="closeCommunityPicker">关闭</text>
				</view>
				<scroll-view scroll-y class="community-list">
					<view class="community-item" v-for="item in communityList" :key="item.id"
						@click="selectCommunity(item)">
						<text class="community-item-name" :class="{ active: currentCommunity.id === item.id }">
							{{ item.name }}
						</text>
						<uni-icons v-if="currentCommunity.id === item.id" type="checkmarkempty" size="24"
							color="#007AFF"></uni-icons>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				services: [],
				loading: true,
				currentCommunity: {}, // 当前选中的小区
				communityList: [], // 用户绑定的小区列表
				telephoneNumber: '', // 用户手机号
			};
		},

		methods: {
			/**
			 * 显示小区选择弹窗。
			 */
			showCommunityPicker() {
				this.$refs.communityPopup.open();
			},

			/**
			 * 关闭小区选择弹窗。
			 */
			closeCommunityPicker() {
				this.$refs.communityPopup.close();
			}
		},

		computed: {
			/**
			 * 计算属性：返回当前选中小区的名称，如果未选择则返回默认提示。
			 */
			communityDisplayName() {
				return this.currentCommunity.name || '未选择小区';
			}
		},

		onLoad() {
			/**
			 * 页面加载时调用，初始化数据。
			 */
			this.initializeData();
		},

		onShow() {
			/**
			 * 页面显示时调用，刷新服务菜单。
			 */
			this.fetchHomeMenus();
		},

		methods: {
			/**
			 * 初始化数据，加载用户小区列表。
			 */
			async initializeData() {
				this.loading = true;
				await this.fetchUserCommunities();
				this.loading = false;
			},

			/**
			 * 获取首页服务菜单。
			 */
			async fetchHomeMenus() {
				try {
					const response = await uni.request({
						url: 'http://localhost:8500//home/queryAllHomeMenu',
						method: 'GET'
					});

					if (response.data.code === 200) {
						this.services = response.data.data;
					} else {
						throw new Error(response.data.message || '获取菜单失败');
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取菜单失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 点击服务卡片时导航到相应页面。
			 * @param {Object} service - 被点击的服务对象。
			 */
			onCardClick(service) {
				if (service.path.includes('/pages/lock/Lock')) {
					// 如果是跳转到开锁页面，携带小区信息
					uni.navigateTo({
						url: `${service.path}?communityId=${this.currentCommunity.id}&communityName=${this.currentCommunity.name}`
					});
				} else {
					uni.navigateTo({
						url: service.path
					});
				}
			},

			/**
			 * 获取用户绑定的小区列表。
			 */
			async fetchUserCommunities() {
				try {
					// 从本地存储获取手机号
					const phoneNumber = uni.getStorageSync('phoneNumber') || '';

					const response = await uni.request({
						url: 'http://localhost:8500/community/locations',
						method: 'GET',
						data: {
							telephoneNumber: phoneNumber // 使用存储的手机号替换硬编码值
						}
					});

					if (response.data.code === 200) {
						this.communityList = response.data.data;
						if (this.communityList.length > 0 && !this.currentCommunity.id) {
							this.currentCommunity = this.communityList[0];
						}
					} else {
						throw new Error(response.data.message || '获取小区列表失败');
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取小区列表失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 显示小区选择弹窗。
			 */
			showCommunityPicker() {
				this.$refs.communityPopup.open();
			},

			/**
			 * 关闭小区选择弹窗。
			 */
			closeCommunityPicker() {
				this.$refs.communityPopup.close();
			},

			/**
			 * 选择小区并关闭弹窗。
			 * @param {Object} item - 被选择的小区对象。
			 */
			selectCommunity(item) {
				this.currentCommunity = item;
				this.closeCommunityPicker();
			}
		}
	}
</script>

<style lang="scss">
	.home-container {
		padding: 20rpx;
		background-color: #f8f8f8;

		.cards-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 30rpx;
			padding: 20rpx;
		}

		.service-card {
			background-color: #fff;
			border-radius: 12rpx;
			padding: 30rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
			transition: transform 0.2s;

			&:hover {
				transform: scale(1.02);
			}

			&.skeleton {
				height: 200rpx;
				background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
				background-size: 200% 100%;
				animation: loading 1.5s infinite;
			}
		}

		.card-icon {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 20rpx;
		}

		.card-content {
			text-align: center;
		}

		.card-title {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}

		.community-wrapper {
			padding: 20rpx 30rpx;
			background-color: #fff;
			margin-bottom: 20rpx;

			.community-info {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.left {
					display: flex;
					align-items: center;

					.community-name {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
						margin-right: 8rpx;
					}
				}

				.switch-btn {
					font-size: 24rpx;
					color: #007AFF;
					padding: 8rpx 20rpx;
					border: 1rpx solid #007AFF;
					border-radius: 24rpx;
					background-color: #f0f8ff;
				}
			}
		}
	}

	@keyframes loading {
		0% {
			background-position: 200% 0;
		}

		100% {
			background-position: -200% 0;
		}
	}

	.popup-content {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: env(safe-area-inset-bottom);

		.popup-header {
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1rpx solid #eee;

			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.popup-close {
				font-size: 28rpx;
				color: #666;
			}
		}

		.community-list {
			max-height: 60vh;

			.community-item {
				padding: 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1rpx solid #eee;

				.community-item-name {
					font-size: 28rpx;
					color: #333;

					&.active {
						color: #007AFF;
						font-weight: bold;
					}
				}
			}
		}
	}
</style>